'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url admin/pages/files_mzgl/dy_tv_series/kh/uploaddj_video 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			_id,
			ma_app_id,
			tv_id,
			title,
			seq,
			cover_list,
			open_video_id
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
		
		let A = await vk.baseDao.selects({
		  dbName:"a_appid",
		  // 主表where条件
		  whereJson:{
		    appid:ma_app_id
		  },
		});
		
		console.log("A========",A);
		
		
		let appsecret = A.rows[0].appsecret

		// 查询短剧
		let TvArr = await vk.baseDao.select({
			dbName: "dy_tv", // 表名
			whereJson: { // 条件
				_id: tv_id // 金额大于0
			},
		});

		console.log("TvArr", TvArr.rows[0]);

		const episode_info_list = [{
			title:title,
			seq:seq,
			cover_list:cover_list,
			open_video_id:open_video_id
		}]


		//获取accessToken
		let urlA = "https://open.douyin.com/oauth/client_token/"
		const accessToken = await uniCloud.httpclient.request(urlA, {
			method: 'POST',
			headers: {
				"Content-Type": "application/json",
			},
			data: {
				client_key: ma_app_id, // id
				client_secret: appsecret, // 密钥
				grant_type: "client_credential",
			},
			dataType: 'json', // 指定返回值为json格式，自动进行parseK
		})


		// 有效时间为 2 个小时
		let access_token = accessToken.data.data.access_token


		let urlT = "https://open.douyin.com/api/playlet/v2/video/edit/"
		let resA =  await uniCloud.httpclient.request(urlT, {
			method: 'POST',
			headers: {
				"Content-Type": "application/json",
				"access-token": access_token,
			},
			data: {
				album_id: TvArr.rows[0].album_id,
				ma_app_id: ma_app_id,
				episode_info_list: episode_info_list
			},
			dataType: 'text', // 指定返回值为json格式，自动进行parseK
		})

		console.log("resA====",resA.data.data);
		
		// 短剧版本
		const version = resA.data.data.version
		
		// 更新数据库版本
		let num = await vk.baseDao.update({
			dbName: "dy_tv", // 表名
			whereJson: { // 条件
				album_id: TvArr.rows[0].album_id,
			},
			dataJson: { // 需要修改的数据
				version: version
			}
		});


		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}